import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/lpnphoto/lpnphotomodel.dart';
import 'package:opene/ui/returns/returnsdialogscreen.dart';
import 'package:opene/ui/returns/returnsmodel.dart';
import 'package:opene/ui/vas/putaway/vasputataylocationscreen.dart';
import 'package:toast/toast.dart';

class VASPutatayScreen extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return VASPutatayPage();
  }
}

class VASPutatayPage extends StatefulWidget {

  @override
  _VASPutatayPageState createState() => _VASPutatayPageState();
}

class _VASPutatayPageState extends BaseState<VASPutatayScreen> {
  String lpnPutawayType = "7";
  List<String> data = new List();

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Putaway";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration(milliseconds: 300), () {
      getWaitingPutawayLpns();
    });
  }

  void setCheck2Show(int value) {
    this.type = value;
    lpnPutawayType = "7";
    switch (type){
      case 1:
        lpnPutawayType = "7";
        break;
      case 2:
        lpnPutawayType ="8";
        break;
      case 3:
        lpnPutawayType = "9";
        break;
    }
    if (data != null) {
      setState(() {
        data.clear();
      });
    }
    getWaitingPutawayLpns();
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 0, top: 10, right: 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Expanded(
                flex: 1, //设置权重
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: EdgeInsets.zero,
                      margin: EdgeInsets.zero,
                      height: 25.0,
                      child: Radio<int>(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        value: 1,
                        groupValue: this.type,
                        activeColor: MyAppTheme.nearlyBlue,
                        onChanged: (value) {
                          setCheck2Show(value);
                        },
                      ),
                    ),
                    GestureDetector(
                      child: Text(
                        "Return_putaway",
                        style: TextStyle(color: this.type == 1 ? MyAppTheme.nearlyBlue : MyAppTheme.color_333333, fontSize: 14.0),
                      ),
                      onTap: () {
                        setCheck2Show(1);
                      },
                    ),
                  ],
                ),
              ),
              Expanded(
                flex: 1, //设置权重
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: EdgeInsets.zero,
                      margin: EdgeInsets.zero,
                      height: 25.0,
                      child: Radio<int>(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        value: 2,
                        groupValue: this.type,
                        activeColor: MyAppTheme.nearlyBlue,
                        onChanged: (value) {
                          setCheck2Show(value);
                        },
                      ),
                    ),
                    GestureDetector(
                      child: Text(
                        "Return_destroy",
                        style: TextStyle(color: this.type == 2 ? MyAppTheme.nearlyBlue : MyAppTheme.color_333333, fontSize: 14.0),
                      ),
                      onTap: () {
                        setCheck2Show(2);
                      },
                    ),
                  ],
                ),
              ),
            ],
          ),

          Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Expanded(
                flex: 1, //设置权重
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: EdgeInsets.zero,
                      margin: EdgeInsets.zero,
                      height: 25.0,
                      child: Radio<int>(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        value: 3,
                        groupValue: this.type,
                        activeColor: MyAppTheme.nearlyBlue,
                        onChanged: (value) {
                          setCheck2Show(value);
                        },
                      ),
                    ),
                    GestureDetector(
                      child: Text(
                        "Inventory_putaway",
                        style: TextStyle(color: this.type == 3 ? MyAppTheme.nearlyBlue : MyAppTheme.color_333333, fontSize: 14.0),
                      ),
                      onTap: () {
                        setCheck2Show(3);
                      },
                    ),
                  ],
                ),
              ),
            ],
          ),

          Container(
            margin: const EdgeInsets.only(left: 15, top: 5, right: 15, bottom: 0),
            width: double.infinity,
            child: ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 35),
              child: TextField(
                controller: textEditingController,
                textInputAction: TextInputAction.search,
                onSubmitted: (String text) {
                  print('Searching for $text');
                  if (Utils.isEmpty(text)) {
                    return;
                  }
                  lpnCheck(text);
                },
                // autofocus: true,
                decoration: InputDecoration(
                  suffixIcon: IconButton(
                    padding: EdgeInsets.all(2.0),
                    icon: Icon(
                      Icons.qr_code_scanner,
                      size: 28,
                      color: MyAppTheme.nearlyBlue,
                    ),
                    onPressed: () {
                      // requestPermissions();
                      // Utils.scanBarcode(context);
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                        return ScanCode();
                      })).then((text) {
                        if (text == null) {
                          return;
                        }
                        setState(() {
                          textEditingController.text = text;
                        });
                        print(text); //拿到扫描结果
                        lpnCheck(text);
                      });
                    },
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: MyAppTheme.nearlyBlue,
                    ),
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点之外的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点时的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  hintText: "scan inbound lpn barcode",
                  filled: true,
                  fillColor: MyAppTheme.white,
                  //隐藏下划线
                  //border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                ),
                onChanged: (text) {
                  code = text;
                },
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, top: 10,bottom: 5),
            child: Text(
              "Waiting for putaway:",
              style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0,),
            ),
          ),

          Expanded(
            child: Container(
              margin: EdgeInsets.only(left: 15, right: 10),
              child: setListView(),
            ),
          ),
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        String lpn = data[index];
        return Column(
          children: [
            Row(
              children: [
                Expanded(
                  flex: 2, //设置权重
                  child: GestureDetector(
                    onTap: () {
                      lpnCheck(lpn);
                    },
                    child: Text(
                      Utils.getStringisEmpty(lpn),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                    ),
                  ),
                ),
              ],
            ),
            Divider(),
          ],
        );
      },
    );
  }

  void getWaitingPutawayLpns() async {
    // 显示加载中对话框
    LoadingIndicator.show(context);

    Map<String, dynamic> map = new HashMap();
    map["inventoryType"] = lpnPutawayType;
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.getWaitingPutawayLpns,params: map);
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      setState(() {
        data = baseResponse.data == null ? null : new List<String>.from(baseResponse.data) as List<String>;
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void lpnCheck(String lpn) async {
    updateHint('');
    Map<String, dynamic> map = new HashMap();
    map["lpn"] = lpn;
    map["inventoryType"] = lpnPutawayType;
    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.tallyWait, params: map);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      PutatayFbaLPN putatayFbaLPN = PutatayFbaLPN.fromJson(baseResponse.data);
      List<PutatayLPN> putatayLPNs = putatayFbaLPN.skuList;
      if (putatayFbaLPN == null) {
        ToastContext().init(context);
        Toast.show("Nothing to deal with SKU", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
      if (putatayLPNs == null) {
        ToastContext().init(context);
        Toast.show("Nothing to deal with SKU", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
      if (putatayLPNs.length == 0) {
        ToastContext().init(context);
        Toast.show("Nothing to deal with SKU", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => VASPutatayLocationScreen(lpn: lpn, lpnPutawayType: lpnPutawayType, putatayLPNs: putatayLPNs)),
      ).then((value) => {
        setState(() {
          textEditingController.text = "";
          hint = "";
        }),
        getWaitingPutawayLpns()
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }

  @override
  void setNext() {
    if (Utils.isEmpty(textEditingController.text)) {
      ToastContext().init(context);
      Toast.show("scan inbound lpn barcode", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      hint = "";
    });
  }
}
